/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.uoc.tdp.server;

import edu.uoc.tdp.common.SubsystemMaintenance;
import edu.uoc.tdp.common.SubsystemConnect;
import edu.uoc.tdp.server.impl.SubsystemConnectImpl;
import edu.uoc.tdp.server.impl.SubsystemMaintenanceImpl;
import java.io.IOException;
import java.net.MalformedURLException;
import java.rmi.*;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.rmi.NoSuchObjectException;
import javax.swing.JOptionPane;

/**
 * @author tomeu
 * @version 1.0
 */
public class Server {

    public Registry registry;

    public static void main(String args[]) throws IOException {

        //Servidor srv = null;
        new Server();
    }

    public Server() {
        try {
            String serverName = "//localhost/";
            registry = LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
            System.out.println("Iniciando servidor RMI...");
            SubsystemMaintenance remoteMaintenance = new SubsystemMaintenanceImpl();
            Naming.rebind(serverName+"remoteMaintenance", remoteMaintenance);
            SubsystemConnect remoteConnect = new SubsystemConnectImpl();
            Naming.rebind(serverName+"remoteConnect", remoteConnect);
            System.out.println("¡Servidor iniciado!");

        } catch (RemoteException e) {
            //No se ha podido conectar con RMI
            System.out.println(e.getMessage());
            JOptionPane.showMessageDialog //  
                    (null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        } catch (MalformedURLException e) {
            //La URL es incorrecta
            e.printStackTrace();
        } catch (Exception e) {
            JOptionPane.showMessageDialog //      
                    (null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    public void finalize() {
        try {
            UnicastRemoteObject.unexportObject(registry, true);
        } catch (NoSuchObjectException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}